<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
use app\admin\model\BusChannelSendConfig as ChannelSendConfigModel;
//通道组
use app\admin\model\BusChannelSimConfig as ChannelSimConfigModel;
//重发
use app\admin\model\BusPlatGroupConfig as PlatGroupModel;
//sim
use app\admin\model\BusPlatResendConfig as PlatResendModel;
//渠道补发（新增）
use app\admin\model\ChannelResendConfig as ChannelResendConfigModel;
//判断平台
function isMmsOrSms() {
	if (request()->module() == 'mms' || session('module_mms') == 1) {
		return 1;
	}
	return 0;
}

function filter_default($value) {
	return htmlspecialchars($value, ENT_NOQUOTES);
}
// 应用公共文件
//检查是否高级渠道
function is_OneCha() {
	if (empty(session('relate_id'))) {
		return false;
	}
	if (session('user_type') == 'channel' && in_array(session('channel_level'), [1, 2, 4])) {
		return true;
	} else {
		return false;
	}
}

//curl请求接口 curl_post(请求地址,请求参数数组)
function curl_post1($url, $data = []) {
	return ['code' => 0];
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	// post数据
	curl_setopt($ch, CURLOPT_POST, 1);
	// post的变量
	if (count($data) > 0) {
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	}
	curl_setopt($ch, CURLOPT_HEADER, 0);
	//设置头部信息
	//执行请求
	$output = curl_exec($ch);

	trace('请求接口ip白名单返回：' . $output, 'info');
	//打印获得的数据
	curl_close($ch);
	return json_decode($output, true);
}

function curl_post($url, $data = []) {
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	// post数据
	curl_setopt($ch, CURLOPT_POST, 1);
	// post的变量
	if (count($data) > 0) {
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
	}
	curl_setopt($ch, CURLOPT_HEADER, 0);
	//设置头部信息
	$headers = array('Content-Type:application/json; charset=utf-8');
	curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
	//执行请求
	$output = curl_exec($ch);
	//打印获得的数据
	curl_close($ch);
	return json_decode($output, true);
}

function curl_delete($url, $data = []) {
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');

	curl_setopt($ch, CURLOPT_HEADER, 0);
	//设置头部信息
	// $headers = array('Content-Type:application/json; charset=utf-8');
	// curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
	//执行请求
	$output = curl_exec($ch);
	//打印获得的数据
	curl_close($ch);
	return json_decode($output, true);
}

/**
 * 导出excel(csv)
 * @data 导出数据
 * @headlist 第一行,列名
 * @fileName 输出Excel文件名
 */
function csv_export($data = array(), $headlist = array(), $fileName) {

	header('Content-Type: application/vnd.ms-excel');
	header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');
	header('Cache-Control: max-age=0');

	//打开PHP文件句柄,php://output 表示直接输出到浏览器
	$fp = fopen('php://output', 'a');

	//输出Excel列名信息
	foreach ($headlist as $key => $value) {
		//CSV的Excel支持GBK编码，一定要转换，否则乱码
		$headlist[$key] = iconv('utf-8', 'gbk', $value);
	}

	//将数据通过fputcsv写到文件句柄
	fputcsv($fp, $headlist);

	//计数器
	$num = 0;

	//每隔$limit行，刷新一下输出buffer，不要太大，也不要太小
	$limit = 100000;

	//逐行取出数据，不浪费内存
	$count = count($data);
	for ($i = 0; $i < $count; $i++) {

		$num++;

		//刷新一下输出buffer，防止由于数据过多造成问题
		if ($limit == $num) {
			ob_flush();
			flush();
			$num = 0;
		}

		$row = $data[$i];
		foreach ($row as $key => $value) {

			if (is_numeric($value) && strlen($value) >= 12) {

				$value = "\t" . $value;
			}

			$row[$key] = iconv('utf-8', 'gbk', $value);
		}

		fputcsv($fp, $row);
	}

}

/**
 * [deleteCache 删除生产者缓存]
 * @author   .guo
 * @DataTime 2019-07-01
 * @param    [type]     $name [缓存模块]
 * @return   [type]           [文字说明]
 */
function deleteCache($name = '') {
	// $cachedel = cache('deleteCache.' . request()->controller() . request()->action());
	// //限制请求次数
	// if ($cachedel) {
	//     if (time() - $cachedel <= 1) {
	//         // trace('第二次不需要了','info');
	//         return '删除缓存成功';
	//     }
	// }

	// $date = date('YmdHis');
	// // $url = 'http://127.0.0.1:8080/SMS/MSG?pwd=' . md5('cxpthcqc' . $date) . '&time=' . $date;
	// $url = 'http://1.14.234.197:9092/SMS/MSG?pwd=' . md5('cxpthcqc' . $date) . '&time=' . $date;

	// $result = curl_delete($url);
	// trace('删除生产者缓存-请求链接：' . $url . '，请求结果：' . json_encode($result, JSON_UNESCAPED_UNICODE), 'info');

	// cache('deleteCache.' . request()->controller() . request()->action(), time(), 2);

	// return '删除缓存成功';
}

/**
 * 连接redis
 * @Author   lf
 * @DateTime 2019-07-29T14:31:16+0800
 * @param    [type]                   $h  [description]
 * @param    [type]                   $p  [description]
 * @param    [type]                   $pw [description]
 * @param    [type]                   $s  [description]
 * @return   [type]                       [description]
 */
function redisCurl($h, $p, $pw, $s) {
	//连接本地的 Redis 服务
	$redis = new \Redis();
	$redis->connect($h, $p);
	$redis->auth($pw); //密码
	$redis->select($s);

	return $redis;

}

//数据处理
function dataProcess($data) {
	$arr = [];
	foreach ($data as $k => $v) {
		$arr[$k] = trim($v);
	}
	return $arr;
}

/**
 * 获取指定日期段内每一天的日期和天数
 * @param  Date  $startdate 开始日期 格式化时间 Y-m-d H:i:s
 * @param  Date  $enddate   结束日期 格式化时间 Y-m-d H:i:s
 * @return Array
 */
function getDateFromRange($startdate, $enddate) {

	$startdate = date('Y-m-d 00:00:00', strtotime($startdate));

	$enddate = date('Y-m-d 23:59:59', strtotime($enddate));

	$stimestamp = strtotime($startdate);

	$etimestamp = strtotime($enddate);

	if ($etimestamp < $stimestamp) {
		return [];
	}

	// 计算日期段内有多少天
	$days = (int) ceil(($etimestamp - $stimestamp) / 86400);

	// 保存每天日期
	$date = array();

	for ($i = 0; $i < $days; $i++) {

		$dateOne = date('Y-m-d', $stimestamp + (86400 * $i));

		$date[] = substr(str_replace("-", "", $dateOne), 2);
	}

	foreach ($date as $key => $value) {
		# code...
		//查询表是否存在
		$istable = Db::query("SHOW TABLES LIKE 'bus_order_{$value}'");

		if (!$istable) {
			unset($date[$key]);
		}
	}

	return array_reverse($date);
}

/**
 * [getMaxPlatIndex 获取通道对应最大的plat_index]
 * @param  [type] $platId [description]
 * @return [type]         [description]
 */
function getMaxPlatIndex($platId) {
	$channelPlatIndex = ChannelSendConfigModel::where('plat_id', $platId)->max('plat_index');
	$resendPlatIndex  = PlatResendModel::where('plat_id_change', $platId)->max('plat_index');
	$groupPlatIndex   = PlatGroupModel::where('plat_id_send', $platId)->max('plat_index');
	//sim补发
	$bfPlatIndex = ChannelSimConfigModel::where('bf_plat_id', $platId)->max('bf_plat_index');
	//sim追尾
	$zwPlatIndex = ChannelSimConfigModel::where('zw_plat_id', $platId)->max('zw_plat_index');
	//渠道补发
	$channelResendPlatIndex = ChannelResendConfigModel::where('plat_id', $platId)->max('plat_index');
	return max($channelPlatIndex, $resendPlatIndex, $groupPlatIndex, $bfPlatIndex, $zwPlatIndex, $channelResendPlatIndex);
}

/**
 * [findPlatIndex 查询plat_index是否已存在]
 * @param  [type] $platId    [description]
 * @param  [type] $platIndex [description]
 * @return [type]            [description]
 */
function findPlatIndex($platId, $platIndex) {
	$channelPlatIndex = ChannelSendConfigModel::where('plat_id', $platId)->where('plat_index', $platIndex)->find();
	$resendPlatIndex  = PlatResendModel::where('plat_id_change', $platId)->where('plat_index', $platIndex)->find();
	$groupPlatIndex   = PlatGroupModel::where('plat_id_send', $platId)->where('plat_index', $platIndex)->find();
	//sim补发
	$bfPlatIndex = ChannelSimConfigModel::where('bf_plat_id', $platId)->where('bf_plat_index', $platIndex)->find();
	//sim追尾
	$zwPlatIndex = ChannelSimConfigModel::where('zw_plat_id', $platId)->where('zw_plat_index', $platIndex)->find();
	//渠道补发
	$channelResendPlatIndex = ChannelResendConfigModel::where('plat_id', $platId)->where('plat_index', $platIndex)->find();
	if ($channelPlatIndex || $resendPlatIndex || $groupPlatIndex || $bfPlatIndex || $zwPlatIndex || $channelResendPlatIndex) {
		return 'true';
	}
	return 'false';
}

/**
 * [modifyQueryPlatIndex 修改plat_index查询]
 * @param  [type] $platId    [description]
 * @param  [type] $platIndex [description]
 * @return [type]            [description]
 */
function modifyQueryPlatIndex($platId, $platIndex, $ccpid) {
	$channelPlatIndex = ChannelSendConfigModel::where('plat_id', $platId)->where('plat_index', $platIndex)->where('id', '<>', $ccpid)->find();
	$resendPlatIndex  = PlatResendModel::where('plat_id_change', $platId)->where('plat_index', $platIndex)->find();
	$groupPlatIndex   = PlatGroupModel::where('plat_id_send', $platId)->where('plat_index', $platIndex)->find();
	//sim补发
	$bfPlatIndex = ChannelSimConfigModel::where('bf_plat_id', $platId)->where('bf_plat_index', $platIndex)->find();
	//sim追尾
	$zwPlatIndex = ChannelSimConfigModel::where('zw_plat_id', $platId)->where('zw_plat_index', $platIndex)->find();
	//渠道补发
	$channelResendPlatIndex = ChannelResendConfigModel::where('plat_id', $platId)->where('plat_index', $platIndex)->find();
	if ($channelPlatIndex || $resendPlatIndex || $groupPlatIndex || $bfPlatIndex || $zwPlatIndex || $channelResendPlatIndex) {
		return 'true';
	}
	return 'false';
}
